package fenetre;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import composantes.*;
import interfaces.Grille;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.border.LineBorder;

public class TabJeu extends JPanel implements ActionListener{
	private Grille		_g;
	
	private JButton[][] _btnGrille;
	private JButton		_btnUpdate,
						_btnReset;
	private JLabel		_src,
						_dst;
	
	private void init(Grille g) throws Exception{
		_btnUpdate = new JButton("Update");
		_btnReset = new JButton("Reset");
		_src = new JLabel();
		_dst = new JLabel();
		
		_btnUpdate.addActionListener(this);
		_btnReset.addActionListener(this);
		_g = g;
		build();
	}
	
	public TabJeu() throws Exception{
		init(null);
	}
	
	public TabJeu(Grille g) throws Exception{
		init(g);
	}
	
	private void build() throws Exception{
		if(_g == null)
			throw new Exception("Exception de grille null");
		
		Dimension dim = new Dimension(_g.getHauteur(), _g.getLargeur());
		JPanel panGrille = new JPanel(new GridLayout(dim.height, dim.width));
		JPanel panBoutons = new JPanel(new FlowLayout());
		setLayout(new BorderLayout());
		
		_btnGrille = new JButton[dim.height][dim.width];
		for(int i = 0; i < dim.height; i++)
			for(int j = 0; j < dim.width; j++){
				_btnGrille[i][j] = new JButton();
				_btnGrille[i][j].setBackground(_g.getColor(i, j));
				_btnGrille[i][j].setBorder(new LineBorder(Color.gray, 1));
				_btnGrille[i][j].setOpaque(true);
				_btnGrille[i][j].addActionListener(this);
				panGrille.add(_btnGrille[i][j]);
			}
		panBoutons.add(_btnUpdate);
		panBoutons.add(_btnReset);
		panBoutons.add(_src);
		panBoutons.add(_dst);
		
		add("Center", panGrille);
		add("South", panBoutons);
	}
	
	private void synchroniser(){
		for(int i = 0; i < _g.getHauteur(); i++){
			for(int j = 0; j < _g.getLargeur(); j++){
//				_btnGrille[i][j].setText(_g.getText(i, j));
				_btnGrille[i][j].setBackground(_g.getColor(i, j));
			}
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		switch(arg0.getActionCommand()){
		case "Update":
			if(_g.canUpdate())
				_g.update();
			break;
		case "Reset":
			_g.clear();
			break;
		default:
			JButton btn = (JButton) arg0.getSource();
			
			for(int i = 0; i < _g.getHauteur(); i++)
				for(int j = 0; j < _g.getLargeur(); j++)
					if(btn == _btnGrille[i][j]){
						_g.caseSelectionnee(i, j);
						if(_g.canUpdate())
							_g.update();
					}
		}
		synchroniser();
	}
}
